package com.tomtop.core.web.config;

import java.util.concurrent.TimeUnit;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;

import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import okhttp3.OkHttpClient.Builder;

@Configuration
@ConditionalOnClass(OkHttpClient.class)
@ConditionalOnMissingBean(ClientHttpRequestFactory.class)
@ConditionalOnMissingClass("org.apache.http.client.HttpClient")
public class OkHttp3RestTemplateConfig {
	
	@Bean ConnectionPool connectionPool(){
		return new ConnectionPool(150, 4000, TimeUnit.SECONDS);
	}

	@Bean Builder okHttpClientBuilder(ConnectionPool connectionPool){
		Builder okHttpClientBuilder=new Builder();
		okHttpClientBuilder.connectionPool(connectionPool);
		return okHttpClientBuilder;
	}
	
	@Bean OkHttpClient httpClient(Builder okHttpClientBuilder){
		return okHttpClientBuilder.build();
	}
	
	@Bean OkHttp3ClientHttpRequestFactory clientHttpRequestFactory(OkHttpClient httpClient){
		OkHttp3ClientHttpRequestFactory okHttp3ClientHttpRequestFactory=new OkHttp3ClientHttpRequestFactory(httpClient);
		okHttp3ClientHttpRequestFactory.setConnectTimeout(8000);
		okHttp3ClientHttpRequestFactory.setWriteTimeout(10000);
		okHttp3ClientHttpRequestFactory.setReadTimeout(1000);
		return okHttp3ClientHttpRequestFactory; 
	}
}
